﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using LitJson;
using visinia.SmartEngine;
using visinia.SmartEngine.Modules;

namespace visinia.web.admin.pages
{
    public partial class ModuleControllerPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((Thread.CurrentPrincipal.IsInRole("designer") || (Thread.CurrentPrincipal.IsInRole("admin"))))
            {
                if (Request.QueryString["AddModule"] != null)
                    AddModule();
                if (Request.QueryString["UpdatePanes"] != null)
                    UpdatePanes();
                if (Request.QueryString["DeleteModule"] != null)
                    DeleteModule();
                if (Request.QueryString["ModuleSettings"] != null)
                    ModuleSettings();
                if (Request.QueryString["SaveSettings"] != null)
                    SaveSettings();
            }
        }

        #region Add Module
        private void AddModule()
        {
            if (Request.QueryString["InstalledModuleId"] == null)
                return;
            int InstalledModuleId = 0;
            Int32.TryParse(Request.QueryString["InstalledModuleId"], out InstalledModuleId);
            int PageId = 0;
            Int32.TryParse(Request.QueryString["PageId"], out PageId);
            string Pane = Request.QueryString["Pane"];
            ModuleInfo module = new ModuleInfo(InstalledModuleId, PageId, Pane);
            int ModuleId = ModuleController.AddModule(module);
            StringWriter writer = new StringWriter();
            WebModuleController.CURRENT_MODE = WebModuleController.MODES.DESIGNER;
            Server.Execute(WebRoots.GetAdminRoot + "Pages/_Modules/InplaceRendering.aspx?ModuleId=" + ModuleId, writer);
            Response.Clear();
            Response.Write(writer.ToString());
            Response.End();
        }
        #endregion

        #region UpdatePanes
        private void UpdatePanes()
        {
            string json = Request.Params["data"];
            if (string.IsNullOrEmpty(json))
                return;
            ModuleAll modulesall = JsonMapper.ToObject<ModuleAll>(json);
            if (UpdateModules(modulesall))
            {
                Response.Clear();
                Response.Write("success");
                Response.End();
            }
        }

        private bool UpdateModules(ModuleAll modulesall)
        {
            if (modulesall.items.Length == 0)
                return true;
            int PageId = 0;
            if (Int32.TryParse(modulesall.items[0].pageid, out PageId))
            {
                List<ModuleInfo> modules = ModuleController.GetModules(PageId);
                foreach (ModuleData module in modulesall.items)
                {
                    ModuleInfo found = modules.Find(p => p.ModuleId.ToString() == module.moduleid);
                    if (found != null)
                    {
                        if ((found.Pane == module.pane) && (found.PaneOrder == module.order))
                            continue;
                        else
                        {
                            found.Pane = module.pane;
                            found.PaneOrder = module.order;
                            ModuleController.UpdateModule(found);
                        }
                    }
                }
                return true;
            }
            return false;
        }
        #endregion

        #region DeleteModule
        private void DeleteModule()
        {
            if (Request.QueryString["ModuleId"] == null)
                return;
            string Module = Request.QueryString["ModuleId"];
            int ModuleId = 0;
            if (Int32.TryParse(Module, out ModuleId))
            {
                ModuleController.DeleteModule(ModuleId);
                Response.Clear();
                Response.Write("success");
                Response.End();
            }
            else
            {
                Response.Clear();
                Response.Write("Error Module can't be deleted");
                Response.End();
            }
        }
        #endregion

        #region ModuleSettings
        private void ModuleSettings()
        {
            if (Request.QueryString["ModuleId"] == null)
                return;
            string ModuleId = Request.QueryString["ModuleId"];
            StringWriter writer = new StringWriter();
            WebModuleController.CURRENT_MODE = WebModuleController.MODES.DESIGNER;
            Server.Execute(WebRoots.GetAdminRoot + "Pages/_Modules/ModuleSettings.aspx?ModuleId=" + ModuleId, writer);
            Response.Clear();
            Response.Write(writer.ToString());
            Response.End();
        }
        #endregion

        #region SaveSettings
        private void SaveSettings()
        {
            string jsonHtmlEncoded = Request.Params["data"];
            if (string.IsNullOrEmpty(jsonHtmlEncoded))
                return;
            string json = Server.HtmlDecode(jsonHtmlEncoded);
            ModuleSettingsData[] modulesall = JsonMapper.ToObject<ModuleSettingsData[]>(json);
            Hashtable settings = new Hashtable();
            foreach (ModuleSettingsData data in modulesall)
            {
                settings.Add(data.name, Server.HtmlDecode(data.value));
            }
            int ModuleId = UpdateModuleSettings(settings);
            if (ModuleId > 0)
            {
                StringWriter writer = new StringWriter();
                WebModuleController.CURRENT_MODE = WebModuleController.MODES.DESIGNER;
                Server.Execute(WebRoots.GetAdminRoot + "Pages/_Modules/InplaceRendering.aspx?ModuleId=" + ModuleId, writer);
                Response.Clear();
                Response.Write(writer.ToString());
                Response.End();
            }
            else
            {
                Response.Clear();
                Response.Write("error");
                Response.End();
            }
        }

        private int UpdateModuleSettings(Hashtable settings)
        {
            if (string.IsNullOrEmpty((string)settings["MODULE_ID"]))
                return 0;
            ModuleInfo info = ModuleController.GetModule(Convert.ToInt32(settings["MODULE_ID"]));
            if (info == null)
                return 0;
            info.Title = (string)settings["MODULE_TITLE"];
            info.TitleImageUrl = (string)settings["MODULE_TITLE_IMAGE_URL"];
            info.TitleImageNavigationUrl = (string)settings["MODULE_TITLE_IMAGE_NAVIGATION_URL"];
            info.Width = Convert.ToInt32(settings["MODULE_WIDTH"]);
            info.Height = Convert.ToInt32(settings["MODULE_HEIGHT"]);
            info.CssClass = (string)settings["MODULE_CSSCLASS"];
            info.Visible = ((string)settings["MODULE_VISIBLE"]) == "True" ? true : false;
            ModuleController.UpdateModule(info);

            if (!string.IsNullOrEmpty(info.ModuleSettingsUrl))
            {
                //save private settings
                WebSettingsModule SettingControl = (WebSettingsModule)LoadControl(WebRoots.GetModulesRoot + info.ModuleSettingsUrl);
                if (SettingControl != null)
                {
                    SettingControl.ModuleId = info.ModuleId;
                    SettingControl.SaveSettings(settings);
                }
            }
            return info.ModuleId;
        }
        #endregion

        #region Utility Classes
        private class ModuleAll
        {
            private ModuleData[] _modules;
            public ModuleData[] items { get { return _modules; } set { _modules = value; } }
        }

        private class ModuleData
        {
            private string _ModuleId;
            public string moduleid { get { return _ModuleId; } set { _ModuleId = value; } }

            private string _PageId;
            public string pageid { get { return _PageId; } set { _PageId = value; } }

            private int _Order;
            public int order { get { return _Order; } set { _Order = value; } }

            private string _PANE;
            public string pane { get { return _PANE; } set { _PANE = value; } }
        }

        private class ModuleSettingsData
        {
            private string _name;
            public string name { get { return _name; } set { _name = value; } }

            private string _value;
            public string value { get { return _value; } set { _value = value; } }

        }
        #endregion
    }
}
